package verify

import (
	"data/config"
	"data/view"
	"net/url"
	"public/mycache"
	"public/myhttp"
	"public/mysqldb"
	"public/tools"
	"strconv"
	"strings"
	"time"
)

//
type VerifyInfo struct {
	view.BaseAccessToken
	Phone   string `json:"phone"`
	Verify  string `json:"verify"`
	UtcTime int64  `json:"utctime"`
}

//
func OnGet(accesstoken string) (info VerifyInfo) {
	//保存缓存
	cache := mycache.OnGetCache("verify")
	tp, ret := cache.Value(accesstoken)
	if ret {
		tmp := tp.(VerifyInfo)
		if (tools.GetUtcTime(time.Now()) - tmp.UtcTime) < 60 {
			info = tmp
		}

		return
	}

	return
	//------------------end
}

//
func OnAdd(info VerifyInfo) {
	info.UtcTime = tools.GetUtcTime(time.Now())
	//保存缓存
	cache := mycache.OnGetCache("verify")
	cache.Add(info.Access_token, info, 1*time.Minute)
	//------------------end
}

//发送消息
func OnSendMsg(phone, key, code string) bool {
	text := GetMsgMdel(key)
	if len(text) > 0 {
		text = strings.Replace(text, "{1}", code, 1)
		return sendMSG(phone, text)
	}

	return false
}

//
func GetMsgMdel(key string) string {
	//保存缓存
	cache := mycache.OnGetCache("msgmodel")
	tp, ret := cache.Value(key)
	if ret {
		return tp.(string)
	}

	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())
	var msg_info Msg_model_tbl
	orm.Where("`key` = ?", key).Find(&msg_info)
	if msg_info.Id > 0 {
		cache.Add(key, msg_info.Context, 24*time.Hour)
	}
	return msg_info.Context
	//------------------end
}

func sendMSG(phone, context string) bool {
	context = tools.GetGBK(context)
	postValues := url.Values{}
	postValues.Set("CorpID", "LKSDK0004999")
	postValues.Set("Pwd", "123456@")
	postValues.Set("Mobile", phone)
	postValues.Set("Content", context)
	//postValues.Set("Mobile", phone)
	bodys := myhttp.OnPostForm("https://mb345.com/ws/BatchSend2.aspx", postValues)

	num, _ := strconv.ParseInt(string(bodys), 10, 64)
	return num > 0
}
